<template>
  <div class="container">
    <Breadcrumb :items="[$t('运营商管理'), $t('提现记录')]" />
    <a-card class="general-card">
      <template #title>
        {{ $t('提现记录管理') }}
      </template>
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="searchForm"
            label-align="left"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-layout="inline"
          >
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="partnerName" :label="$t('运营商名称')">
                  <a-input v-model="searchForm.partnerName" :placeholder="$t('请输入运营商名称')" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="withdrawNo" :label="$t('提现编号')">
                  <a-input v-model="searchForm.withdrawNo" :placeholder="$t('请输入提现编号')" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="withdrawStatus" :label="$t('提现状态')">
                  <a-select v-model="searchForm.withdrawStatus" :placeholder="$t('请选择提现状态')" allow-clear>
                    <a-option :value="WithdrawStatus.APPLYING">{{ $t('申请中') }}</a-option>
                    <a-option :value="WithdrawStatus.APPROVED">{{ $t('审核通过') }}</a-option>
                    <a-option :value="WithdrawStatus.PAID">{{ $t('已打款') }}</a-option>
                    <a-option :value="WithdrawStatus.COMPLETED">{{ $t('已完成') }}</a-option>
                    <a-option :value="WithdrawStatus.REJECTED">{{ $t('已拒绝') }}</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="paymentMethod" :label="$t('打款方式')">
                  <a-select v-model="searchForm.paymentMethod" :placeholder="$t('请选择打款方式')" allow-clear>
                    <a-option :value="PaymentMethod.BANK">{{ $t('银行转账') }}</a-option>
                    <a-option :value="PaymentMethod.WECHAT">{{ $t('微信') }}</a-option>
                    <a-option :value="PaymentMethod.ALIPAY">{{ $t('支付宝') }}</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="timeRange" :label="$t('申请时间')">
                  <a-range-picker
                    v-model="timeRange"
                    style="width: 100%"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-space>
                  <a-button type="primary" @click="search">
                    <template #icon>
                      <icon-search />
                    </template>
                    {{ $t('搜索') }}
                  </a-button>
                  <a-button @click="reset">
                    <template #icon>
                      <icon-refresh />
                    </template>
                    {{ $t('重置') }}
                  </a-button>
                </a-space>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 32px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="horizontal" size="medium">
            <a-button type="primary" @click="openCreateDialog">
              <template #icon>
                <icon-plus />
              </template>
              {{ $t('新增') }}
            </a-button>
            <a-button type="primary" status="success" @click="exportData">
              <template #icon>
                <icon-download />
              </template>
              {{ $t('导出') }}
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      <a-table
        row-key="id"
        :loading="loading"
        :pagination="pagination"
        :columns="columns"
        :data="renderData"
        :bordered="false"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <template #withdrawStatus="{ record }">
          <a-tag 
            :color="getStatusColor(record.withdrawStatus)" 
            size="medium">
            {{ record.withdrawStatusName }}
          </a-tag>
        </template>
        <template #paymentMethod="{ record }">
          <a-tag size="medium">
            {{ record.paymentMethodName }}
          </a-tag>
        </template>
        <template #withdrawAmount="{ record }">
          <span style="color: #165DFF; font-weight: bold;">
            {{ record.withdrawAmount ? '¥' + record.withdrawAmount.toFixed(2) : '-' }}
          </span>
        </template>
        <template #actualAmount="{ record }">
          <span style="color: #FF5722; font-weight: bold;">
            {{ record.actualAmount ? '¥' + record.actualAmount.toFixed(2) : '-' }}
          </span>
        </template>
        <template #operations="{ record }">
          <a-space>
            <a-button type="text" size="small" @click="viewDetail(record)">
              <template #icon><icon-eye /></template>
              {{ $t('详情') }}
            </a-button>
            <a-button 
              v-if="record.withdrawStatus === WithdrawStatus.APPLYING" 
              type="text" 
              size="small" 
              @click="reviewWithdraw(record, true)">
              <template #icon><icon-check-circle /></template>
              {{ $t('通过') }}
            </a-button>
            <a-button 
              v-if="record.withdrawStatus === WithdrawStatus.APPLYING" 
              type="text" 
              status="danger" 
              size="small" 
              @click="reviewWithdraw(record, false)">
              <template #icon><icon-close-circle /></template>
              {{ $t('拒绝') }}
            </a-button>
            <a-button 
              v-if="record.withdrawStatus === WithdrawStatus.APPROVED" 
              type="text" 
              status="success" 
              size="small" 
              @click="openPaymentDialog(record)">
              <template #icon><icon-check /></template>
              {{ $t('确认打款') }}
            </a-button>
            <a-button 
              v-if="record.withdrawStatus === WithdrawStatus.PAID" 
              type="text" 
              size="small" 
              @click="completeWithdraw(record)">
              <template #icon><icon-check-circle /></template>
              {{ $t('完成提现') }}
            </a-button>
            <a-button type="text" status="danger" size="small" @click="confirmDelete(record)">
              <template #icon><icon-delete /></template>
              {{ $t('删除') }}
            </a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>
    
    <!-- 新增/编辑提现记录对话框 -->
    <WithdrawForm
      :visible="formVisible"
      :record="currentRecord"
      :isEdit="isEdit"
      @update:visible="(val: boolean) => formVisible = val"
      @success="handleFormSuccess"
    />
    
    <!-- 提现详情对话框 -->
    <WithdrawDetail
      :visible="detailVisible"
      :record="currentRecord"
      @update:visible="(val: boolean) => detailVisible = val"
    />
    
    <!-- 审核对话框 -->
    <ReviewForm
      :visible="reviewVisible"
      :record="currentRecord"
      :approved="approveStatus"
      @update:visible="(val: boolean) => reviewVisible = val"
      @success="handleReviewSuccess"
    />
    
    <!-- 确认打款对话框 -->
    <PaymentConfirmForm
      :visible="paymentVisible"
      :record="currentRecord"
      @update:visible="(val: boolean) => paymentVisible = val"
      @success="handlePaymentSuccess"
    />
  </div>
</template>

<script lang="ts" setup>
import { computed, ref, reactive, onMounted } from 'vue';
import { Message, Modal } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import {
  WithdrawStatus,
  PaymentMethod,
  PartnerWithdrawQuery,
  PartnerWithdrawVO,
  getPartnerWithdrawPage,
  deletePartnerWithdraw,
  exportPartnerWithdraw,
  completeWithdraw as completeWithdrawApi
} from '@/api/partner/withdraw';
import WithdrawForm from './components/withdraw-form.vue';
import WithdrawDetail from './components/withdraw-detail.vue';
import ReviewForm from './components/review-form.vue';
import PaymentConfirmForm from './components/payment-confirm-form.vue';

// 加载状态
const { loading, setLoading } = useLoading();

// 对话框状态
const formVisible = ref(false);
const detailVisible = ref(false);
const reviewVisible = ref(false);
const paymentVisible = ref(false);
const isEdit = ref(false);
const currentRecord = ref<PartnerWithdrawVO | null>(null);
const approveStatus = ref(false);

// 日期范围
const timeRange = ref<string[]>([]);

// 表格列定义
const columns = computed(() => [
  {
    title: '提现编号',
    dataIndex: 'withdrawNo',
    width: 150,
    ellipsis: true,
    tooltip: true,
  },
  {
    title: '运营商名称',
    dataIndex: 'partnerName',
    width: 120,
    ellipsis: true,
    tooltip: true,
  },
  {
    title: '提现金额(元)',
    dataIndex: 'withdrawAmount',
    width: 120,
    slotName: 'withdrawAmount',
  },
  {
    title: '实际到账(元)',
    dataIndex: 'actualAmount',
    width: 120,
    slotName: 'actualAmount',
  },
  {
    title: '提现状态',
    dataIndex: 'withdrawStatus',
    width: 120,
    slotName: 'withdrawStatus',
  },
  {
    title: '打款方式',
    dataIndex: 'paymentMethod',
    width: 100,
    slotName: 'paymentMethod',
  },
  {
    title: '收款人姓名',
    dataIndex: 'paymentName',
    width: 100,
    ellipsis: true,
    tooltip: true,
  },
  {
    title: '提现申请时间',
    dataIndex: 'createTime',
    width: 160,
  },
  {
    title: '操作',
    dataIndex: 'operations',
    slotName: 'operations',
    width: 250,
    fixed: 'right',
  },
]);

// 表格数据
const renderData = ref<PartnerWithdrawVO[]>([]);

// 分页参数
const basePagination = {
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
  showPageSize: true,
};
const pagination = reactive({
  ...basePagination,
});

// 搜索表单
const searchForm = reactive<PartnerWithdrawQuery>({
  pageNum: 1,
  pageSize: 10,
  partnerName: '',
  withdrawNo: '',
  withdrawStatus: undefined,
  paymentMethod: undefined,
  startTime: undefined,
  endTime: undefined,
});

// 获取状态颜色
function getStatusColor(status: number | undefined) {
  if (status === undefined) return '';
  
  switch (status) {
    case WithdrawStatus.APPLYING:
      return 'blue';       // 申请中
    case WithdrawStatus.APPROVED:
      return 'orange';     // 审核通过
    case WithdrawStatus.PAID:
      return 'cyan';       // 已打款
    case WithdrawStatus.COMPLETED:
      return 'green';      // 已完成
    case WithdrawStatus.REJECTED:
      return 'red';        // 已拒绝
    default:
      return 'gray';
  }
}

// 搜索
function search() {
  fetchData();
}

// 重置搜索条件
function reset() {
  searchForm.partnerName = '';
  searchForm.withdrawNo = '';
  searchForm.withdrawStatus = undefined;
  searchForm.paymentMethod = undefined;
  timeRange.value = [];
  fetchData();
}

// 分页变化
function onPageChange(current: number) {
  pagination.current = current;
  fetchData();
}

// 每页条数变化
function onPageSizeChange(pageSize: number) {
  pagination.pageSize = pageSize;
  pagination.current = 1;
  fetchData();
}

// 打开创建对话框
function openCreateDialog() {
  isEdit.value = false;
  currentRecord.value = null;
  formVisible.value = true;
}

// 查看详情
function viewDetail(record: PartnerWithdrawVO) {
  currentRecord.value = record;
  detailVisible.value = true;
}

// 打开审核对话框
function reviewWithdraw(record: PartnerWithdrawVO, approved: boolean) {
  currentRecord.value = record;
  approveStatus.value = approved;
  reviewVisible.value = true;
}

// 打开确认打款对话框
function openPaymentDialog(record: PartnerWithdrawVO) {
  currentRecord.value = record;
  paymentVisible.value = true;
}

// 完成提现
async function completeWithdraw(record: PartnerWithdrawVO) {
  if (!record.id) return;
  
  Modal.confirm({
    title: '确认操作',
    content: `确定要将提现记录 "${record.withdrawNo}" 标记为已完成吗？`,
    onOk: async () => {
      setLoading(true);
      try {
        await completeWithdrawApi(record.id!);
        Message.success('操作成功');
        fetchData();
      } catch (error) {
        console.error('完成提现失败:', error);
        Message.error('操作失败');
      } finally {
        setLoading(false);
      }
    },
  });
}

// 确认删除
function confirmDelete(record: PartnerWithdrawVO) {
  if (!record.id) return;
  
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除提现记录 "${record.withdrawNo}" 吗？此操作不可恢复。`,
    onOk: async () => {
      setLoading(true);
      try {
        await deletePartnerWithdraw(record.id!);
        Message.success('删除成功');
        // 如果当前页只有一条数据，则返回上一页
        if (renderData.value.length === 1 && pagination.current > 1) {
          pagination.current -= 1;
        }
        fetchData();
      } catch (error) {
        console.error('删除提现记录失败:', error);
        Message.error('删除失败');
      } finally {
        setLoading(false);
      }
    },
  });
}

// 导出数据
function exportData() {
  // 处理日期范围
  const params = { ...searchForm };
  if (timeRange.value && timeRange.value.length === 2) {
    params.startTime = timeRange.value[0];
    params.endTime = timeRange.value[1];
  }
  
  setLoading(true);
  exportPartnerWithdraw(params)
    .then((res) => {
      // 检查响应类型
      if (!(res instanceof Blob)) {
        throw new Error('导出失败：响应格式错误');
      }
      
      // 创建blob对象，保持原始的MIME类型
      const blob = new Blob([res], { type: res.type });
      
      // 创建下载链接
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      
      // 设置文件名
      const currentDate = new Date().toISOString().split('T')[0];
      const fileName = `提现记录_${currentDate}.xls`;
      link.setAttribute('download', fileName);
      
      // 触发下载
      document.body.appendChild(link);
      link.click();
      
      // 清理
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      
      Message.success('导出成功');
    })
    .catch((error) => {
      console.error('导出提现记录失败:', error);
      Message.error(error.message || '导出失败');
    })
    .finally(() => {
      setLoading(false);
    });
}

// 处理表单提交成功
function handleFormSuccess() {
  formVisible.value = false;
  fetchData();
}

// 处理审核成功
function handleReviewSuccess() {
  reviewVisible.value = false;
  fetchData();
}

// 处理打款确认成功
function handlePaymentSuccess() {
  paymentVisible.value = false;
  fetchData();
}

// 获取提现记录数据
async function fetchData() {
  setLoading(true);
  try {
    // 处理日期范围
    const params = { ...searchForm };
    params.pageNum = pagination.current;
    params.pageSize = pagination.pageSize;
    
    if (timeRange.value && timeRange.value.length === 2) {
      params.startTime = timeRange.value[0];
      params.endTime = timeRange.value[1];
    }
    
    const res = await getPartnerWithdrawPage(params);
    renderData.value = res.data.records;
    pagination.total = res.data.total;
  } catch (error) {
    console.error('获取提现记录列表失败:', error);
    Message.error('获取提现记录列表失败');
  } finally {
    setLoading(false);
  }
}

onMounted(() => {
  fetchData();
});
</script>

<style scoped lang="less">
.container {
  padding: 0 20px 20px 20px;
}

.general-card {
  :deep(.arco-card-header) {
    padding: 20px;
  }
  :deep(.arco-card-body) {
    padding: 0 20px 20px 20px;
  }
}
</style> 